package com.jungle.system.config;

import com.jungle.system.utils.oss.MinioUploadUtil;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class InitSequenceBean implements InitializingBean {

    @Resource
    private MinioClient minioClient;
    @Autowired
    private MinioUploadUtil minioUtil;
    @Autowired
    private MinioConfig prop;

    @Override
    public void afterPropertiesSet() {
        String bucketName =prop.getBucketName();
        try {
            if (!minioUtil.bucketExists(bucketName)) {
                minioUtil.makeBucket(bucketName);
                String policyJson = "{\n" +
                        "    \"Version\": \"2012-10-17\",\n" +
                        "    \"Statement\": [\n" +
                        "        {\n" +
                        "            \"Effect\": \"Allow\",\n" +
                        "            \"Action\": [\n" +
                        "                \"s3:*\"\n" +
                        "            ],\n" +
                        "            \"Resource\": [\n" +
                        "                \"arn:aws:s3:::*\"\n" +
                        "            ]\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());
                log.info("jungle----buckets：【{}】,创建[readwrite]策略成功！", bucketName);
            } else {
                log.info("jungle----minio bucket->>>【{}】already exists", bucketName);
            }
        } catch (Exception e) {
            log.debug("jungle----minio bucket->>>【{}】 created filed", bucketName);
            e.printStackTrace();
        }

    }
}
